package com.framework.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.framework.core.domain.AjaxJson;
import com.framework.core.exception.BusinessException;
import com.framework.core.exception.ExceptionUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 异常统一处理
 */
public class CustomExceptionResolver extends
        SimpleMappingExceptionResolver {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //解析错误码
        RequestContext requestContext = new RequestContext(request);
        String errorCode = "";
        if (ex instanceof BusinessException) {
            errorCode = ex.getMessage();
        } else {
            errorCode = ExceptionUtil.getErrorCode(ex);
        }
        String errorMessage = requestContext.getMessage(errorCode);

        if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
                .getHeader("X-Requested-With") != null && request
                .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            // 如果不是异步请求
            // Apply HTTP status code for error views, if specified.
            // Only apply it if we're processing a top-level request.
            String viewName = determineViewName(ex, request);
            if (viewName == null) {
                viewName = "error/error";//默认格式
            }
            Integer statusCode = determineStatusCode(request, viewName);
            if (statusCode != null) {
                applyStatusCodeIfPossible(request, response, statusCode);
            }
            return getModelAndView(viewName, ex, request);
        } else {// JSON格式返回
            ModelAndView empty = new ModelAndView();
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-store");
            response.setCharacterEncoding("UTF-8");
            AjaxJson json = new AjaxJson();
            json.setSuccess(false);
            json.setMsg(errorMessage);
            try {
                PrintWriter pw = response.getWriter();
                pw.write(JSON.toJSONString(json));
                pw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            empty.clear();
            return empty;
        }
    }


}